package vin.pth.authorization.manager;

import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import vin.pth.authorization.enums.AuthorizationErrorCode;
import vin.pth.authorization.exception.AuthorizationException;
import vin.pth.authorization.provider.AuthorizationProvider;
import vin.pth.base.pojo.Authentication;

/**
 * 鉴权管理器.
 *
 * @author cocoon
 */
@RequiredArgsConstructor
@Component
public class AuthorizationManager {

  private final List<AuthorizationProvider> matcherList;

  /**
   * 鉴权管理器的认证方法，会从 AuthorizationProvider 集合中，选择一个匹配的进行认证，如认证失败则抛出异常.
   *
   * @param param 认证参数.
   * @return 认证成功的对象
   * @throws AuthorizationException 认证失败异常
   */
  public Authentication authenticate(Map<String, Object> param) throws AuthorizationException {
    for (AuthorizationProvider provider : matcherList) {
      if (provider.supports(param)) {
        return provider.authenticate(param);
      }
    }
    throw new AuthorizationException(AuthorizationErrorCode.UNKNOWN_CREDENTIALS);
  }


}
